package com.tingyuge.thinking.spring.validation;

import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.context.MessageSource;
import org.springframework.context.support.StaticMessageSource;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import java.util.List;
import java.util.Locale;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/12/12
 * @description
 */
public class ErrorsMessageDemo {

    public static void main(String[] args) {
        //0.创建User对象
        User user = new User();
        user.setName("xiaodao");
        //1.选择 errors -->
        Errors errors = new BeanPropertyBindingResult(user, "user");
        //2.调用 reject 或者 objectValue
        // reject 生成objectErrors
        //rejectValue 生成  fieldErrors
        errors.reject("user.properties.not.null");

        errors.rejectValue("name","name.required");
        //3.获取errors 中 ObjectErrors 和 fieldError
        ObjectError globalError = errors.getGlobalError();
        FieldError fieldError = errors.getFieldError();
        List<ObjectError> allErrors = errors.getAllErrors();
        //4.通过 objectError 中fieldError 中的 code 和 args 来关联 messageSource 来源
        MessageSource messageSource = createMessageSource();

        for (ObjectError allError : allErrors) {
            String message = messageSource.getMessage(allError.getCode(), allError.getArguments(), Locale.getDefault());
            System.out.println(message);
        }

    }

     static MessageSource createMessageSource() {
        StaticMessageSource staticMessageSource = new StaticMessageSource();
        staticMessageSource.addMessage("name.required", Locale.getDefault(),"the name of User must not be null");
        staticMessageSource.addMessage("id.required", Locale.getDefault(),"the id of User must not be null");
        staticMessageSource.addMessage("user.properties.not.null", Locale.getDefault(),"user属性不能为空!");
        return staticMessageSource;


    }
}
